<?php

class wgFixturesTask extends sfBaseTask
{
  protected function configure()
  {
    // // add your own arguments here
     $this->addArguments(array(
     	new sfCommandArgument('after', sfCommandArgument::REQUIRED, 'Model to use for generating fixture file'),
     	new sfCommandArgument('model', sfCommandArgument::OPTIONAL, 'Model to use for generating fixture file'),
     ));

    $this->namespace        = 'wg';
    $this->name             = 'fixtures';
    $this->briefDescription = '';
    $this->detailedDescription = <<<EOF
The [wg:fixture|INFO] task does things.
Call it with:

  [php symfony wg:load-data|INFO]
EOF;
  }

  protected function execute($arguments = array(), $options = array())
  {
  	foreach ($arguments as $name=>$value) $$name = $value;
  	
  	$fixtures = sfConfig::get('sf_data_dir').DIRECTORY_SEPARATOR.'fixtures'.DIRECTORY_SEPARATOR;
  	$files = scandir($fixtures);
//  	$position = substr(basename($afterFile), 0, strpos(basename($afterFile), '-'));
//  	echo $position;
//  	$this->log('Rewrite needed!');
 	 if (isset($model)) {
	    $i = 0;
	    while (!strpos($files[$i], '-'.$after.'.yml') && $i < count($files)) $i++;
	    if ($i == count($files)) {
	      $this->log($after.' was not found in fixtures');
	      exit;
	    }
    } else {
      $i = count($files)-1;
      $model = $after;
    }
    $hyphenPosition = strpos($files[$i], '-');
    $basenum = (int)substr($files[$i], 0, $hyphenPosition);
    $basenum++;
    $fp = fopen($fixtures.sprintf('%02d', $basenum).'-'.$model.'.yml', 'w');
  	fwrite($fp, sfInflector::camelize($model).':');
  	fclose($fp);
  	for ($i++; $i < count($files); $i++) {
  		$basename = basename($files[$i]);
  		$hyphenPosition = strpos($basename, '-');
  		$basenum = (int)substr($basename, 0, $hyphenPosition);
  		$name = substr($basename, $hyphenPosition);
  		$basenum++;
  		rename($fixtures.$files[$i], $fixtures.sprintf('%02d', $basenum).$name);
  	}
  }
}
